package com.xflib.framework.common;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.net.URLDecoder;

public class ApplicationContext {

    //private  static final StreamGobblerMonitor streamGobblerMonitor = new StreamGobblerMonitor();

    public static String getPid() {
        try {
            String jvmName = ManagementFactory.getRuntimeMXBean().getName();
            return jvmName.split("@")[0];
        } catch (Throwable var2) {
            return null;
        }
    }

//    /**
//     * 获取 启动类 所在目录路径字符串
//     * @return
//     * @throws UnsupportedEncodingException
//     */
//    public static String getApplicationHome() throws UnsupportedEncodingException {
//        return getApplicationHome(ClassLoader.getSystemClassLoader().getClass());
//    }

    /**
     * 获取 class 所在目录路径字符串，末尾已包含 {@link File#separator}
     * @param clazz
     * @return
     */
    public static String getApplicationHome(Class clazz) throws UnsupportedEncodingException {
        String configFileName=new File(clazz.getProtectionDomain().getCodeSource().getLocation().getFile()).getParent();
        configFileName = (URLDecoder.decode(configFileName, "UTF-8"));
        while (configFileName.contains(File.separator.concat("classes").concat(File.separator))) {
            configFileName = new File(configFileName).getParent();
        }
        while (configFileName.contains(File.separator.concat("BOOT-INF").concat(File.separator))) {
            configFileName = new File(configFileName).getParent();
        }
        if (!configFileName.endsWith(File.separator)) configFileName=configFileName.concat(File.separator);

        return configFileName;
    }

    private static boolean terminated = false;


    public static boolean isTerminated() {
        return terminated;
    }

    public static void setTerminated(boolean terminated) {
        ApplicationContext.terminated = terminated;
    }

    {

    }
}
